package com.threeti.jiayusms.infrastructure.communicationvoice;

import static org.hibernate.criterion.Restrictions.disjunction;
import static org.hibernate.criterion.Restrictions.like;
import static org.springframework.util.CollectionUtils.isEmpty;

import java.util.List;

import org.hibernate.SessionFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Junction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.threeti.jiayusms.domain.model.CommunicationVoice;
import com.threeti.jiayusms.framework.dao.AbstractCustomKeyDao;
import com.threeti.jiayusms.framework.util.DynaSearchCriteria;
import com.threeti.jiayusms.framework.util.PagedListHandler;
import com.threeti.jiayusms.interfaces.VoiceTemplateDynaCriteriaDto;

@Repository
public class CommunicationVoiceDaoImpl extends AbstractCustomKeyDao<String, CommunicationVoice> implements CommunicationVoiceDao {
	@Autowired
	public CommunicationVoiceDaoImpl(SessionFactory sessionFactory) {
		super(sessionFactory);
	}

	@Override
	protected DetachedCriteria buildDefaultCriteria() {
		return DetachedCriteria.forClass(CommunicationVoice.class);
	}
	
	
	@Override
	public PagedListHandler<CommunicationVoice> findAllVoiceTemplatesByPage(int currentPageIndex, int startingIndex) {
    PagedListHandler<CommunicationVoice> pagedListHandler = this.findAllByPage(currentPageIndex, startingIndex);
    List<CommunicationVoice> pagedList = pagedListHandler.getPageList();
    if (!isEmpty(pagedList))  return pagedListHandler;

    return PagedListHandler.EMPTY_LIST;
	}
	
	@Override
	public PagedListHandler<CommunicationVoice> findVoiceTemplatesByPage(DynaSearchCriteria dynaSearchCriteria, int currentPageIndex, int startingIndex) {
		VoiceTemplateDynaCriteriaDto dynaCriteria = (VoiceTemplateDynaCriteriaDto)dynaSearchCriteria;
		String templateKeywords = dynaCriteria.getTemplateKeywords();

		//模糊查询
		DetachedCriteria criteria = buildDefaultCriteria();
		String[] keywords = templateKeywords.split(" ");
		Junction orClause = disjunction();
		for (int i = 0; i < keywords.length; i++) {
			String keyword = "%" + keywords[i] + "%";
			orClause.add(like("this.customId", keyword).ignoreCase());
		}
		criteria.add(orClause);

		PagedListHandler<CommunicationVoice>  pagedListHandler = this.findByPage(criteria, currentPageIndex, startingIndex);
    List<CommunicationVoice> pagedList = pagedListHandler.getPageList();
    if (!isEmpty(pagedList))  return pagedListHandler;

    return PagedListHandler.EMPTY_LIST;
	}
}
